package com.eorchis.util.excel;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

 /**
 * Title: ExcelBean<br>
 * Description: Excel解析对象<br>
 * Copyright @ 2011~2015 Goldgov .All rights reserved.<br>
 * 
 * @author LuanKW
 * @createDate 2015-5-11
 * @version $Revision: $
 */
public class ExcelBean<T> {
	
	private Class<T> entity;
	
	// Excel中的列(cell)对应属性名称
	protected Map<Integer,String> cellWithPropertyMap = new HashMap<Integer,String>();

	// 属性解析规则
	protected Map<String,ExcelRules> rulesMap = new HashMap<String,ExcelRules>();
	
	// 错误信息
	protected StringBuffer errorMessage;
	
	/**
	 * 错误信息显示分割方式，继承类可扩展
	 * 
	 * @return
	 */
	public String errorMessageSplit(){
		return "\n";
	}
	
	public ExcelBean(){
		try {
			initMap();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    @SuppressWarnings("unchecked")  
    public void initMap() throws Exception{  
	   
        entity = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass())  
                .getActualTypeArguments()[0];  
          
        if(this.entity!=null){  
            Field[] fields = entity.getDeclaredFields();  
            for(Field f : fields){  
                // 获取字段中包含ExcelFieldMeta的注解  
                ExcelFieldMeta meta = f.getAnnotation(ExcelFieldMeta.class);  
                if(meta!=null){
                	if(!cellWithPropertyMap.containsKey(meta.cell())){
	                	// 填装cell对应属性规则
	                	cellWithPropertyMap.put(meta.cell(),f.getName());
	                	// 填装解析规则，含：属性类型、异常提示信息、是否允许为空、属性最大长度、日期转换格式
	                	rulesMap.put(f.getName(),new ExcelRules(f.getType(),meta.errorMessage(), meta.nullAble(), meta.maxLength(), meta.dateFormat()));
                	}else{
                		throw new Exception("com.eorchis.cmdportal.util.ExcelBean.initMap(), Repeating elements! cell:"+meta.cell());
                	}
                }  
            }  
        }  
    }  

	/**
	 * @return the cellWithPropertyMap
	 */
	public Map<Integer, String> getCellWithPropertyMap() {
		return cellWithPropertyMap;
	}

	/**
	 * @return the rulesMap
	 */
	public Map<String, ExcelRules> getRulesMap() {
		return rulesMap;
	}

	/**
	 * @return the errorMessage
	 */
	public StringBuffer getErrorMessage() {
		if(errorMessage == null){
			errorMessage = new StringBuffer();
		}
		return errorMessage;
	}

	/**
	 * @param errorMessage the errorMessage to set
	 */
	public void setErrorMessage(StringBuffer errorMessage) {
		this.errorMessage = errorMessage;
	}
	
}
